package com.kelai.jms.handel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import com.kelai.jms.RedisMessage;
import com.kelai.jms.RedisMessageService;

/**
 * 消息异步执行基类
 * Created by Luffy on 2017/08/17.
 */
public abstract class RedisMessageDelegateHandle<REQ extends RedisMessage, RES> {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisMessageDelegateHandle.class);

    @Autowired
    protected RedisMessageService redisMessageService;

    @Autowired
    protected RedisTemplate<String, REQ> redisTemplate;

    public void handleMessage(REQ req) {
        RES res = null;
        boolean status = false;
        try {
            before(req);
            status = true;
        } catch (Exception ex) {
            LOGGER.error("before ERROR:", ex);
        }
        if (!status) {
            return;
        }
        try {
            status = false;
            res = doExecute(req);
            status = true;
        } catch (Exception ex) {
            LOGGER.error("doExecute ERROR:", ex);
            try {
                rollback(req);
                status = true;
            } catch (Exception _ex) {
                LOGGER.error("rollback ERROR:", _ex);
            }
        }
        if (!status) {
            return;
        }
        try {
            after(req, res);
        } catch (Exception ex) {
            LOGGER.error("after ERROR:", ex);
            try {
                rollback(req, res);
            } catch (Exception _ex) {
                LOGGER.error("rollback ERROR:", _ex);
            }
        }
    }

    protected void before(REQ req) throws Exception{}

    protected abstract RES doExecute(REQ req) throws Exception;

    protected void after(REQ req, RES res) throws Exception {}

    protected void rollback(REQ req) throws Exception {}

    protected void rollback(REQ req, RES res) throws Exception {}

}
